import React, { useMemo, useState, useEffect, useRef } from "react";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Alert,
  Platform,
  Pressable,
  Image,
  TouchableHighlight,
  SafeAreaView,
  Modal,
  ImageBackground,
  Linking
} from "react-native";
import { AddTaskButton } from "../../components/AddRecordButton";
import { Category } from "../../components/Category";
import { useFocusEffect, useRoute } from "@react-navigation/native";
import { TasksList } from "./TasksList";
import { useGlobal } from "../../utils/GlobalContext";
import * as S from "./styles";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Header from "./Header";
import { NativeBaseProvider } from "native-base";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {versionUpgrade} from "../../services/index";



const VersionModal = ()=>{
  const { state, dispatch } = useGlobal();

  useEffect(() => {
    getVersion(true)    
    
  }, []);
   
  const [modalVisible, setModalVisible] = useState(false);
  const [versionInfo, setVersionInfo] = useState({});

  const getVersion =  async (type:boolean)=>{
    let primaryVersionCodeLoc = await AsyncStorage.getItem('primaryVersionCode')
    let secondryVersionCodeLoc = await AsyncStorage.getItem('secondryVersionCode')
    let tertiaryVersionCodeLoc = await AsyncStorage.getItem('tertiaryVersionCode')

    let obj = {
      appType:Platform.OS === 'android' ? '0' : '1'
      // appType:1
    }
    versionUpgrade(obj).then((res)=>{      
      if(res && res.data){
        const { primaryVersionCode,secondryVersionCode,tertiaryVersionCode} = res.data
        if(type){
          if(primaryVersionCodeLoc){
            if(primaryVersionCodeLoc != primaryVersionCode || secondryVersionCodeLoc != secondryVersionCode || tertiaryVersionCodeLoc != tertiaryVersionCode){
              setVersionInfo(res.data)
              setModalVisible(true) 
            }
          }else{
            if(primaryVersionCode != state.primaryVersionCode || secondryVersionCode != state.secondryVersionCode || tertiaryVersionCode != state.tertiaryVersionCode){
              setVersionInfo(res.data)
              setModalVisible(true) 
            }
          }
        }else{
          if(primaryVersionCode != state.primaryVersionCode || secondryVersionCode != state.secondryVersionCode || tertiaryVersionCode != state.tertiaryVersionCode){
            setVersionInfo(res.data)
            setModalVisible(true) 
          }
        }
        


      }
      // if(res && res.data && (res.data.upgradeMode == 1||res.data.upgradeMode == 0)){
      //   setVersionInfo(res.data)
      //   setModalVisible(true)
      // }
      
    }).catch((res)=>{
      console.log(res)
    })
  }


  return (
    <View>
      {/* <TouchableOpacity onPress={()=>{
        getVersion(false) 
      }}>
        <Text>123</Text>
      </TouchableOpacity> */}
      <MadalScreenVersion  versionInfo={versionInfo} modalVisible={modalVisible} setModalVisible={setModalVisible}/>
    </View>
  )
}


const MadalScreenVersion = ({ modalVisible, setModalVisible,versionInfo }: any) => {


  const { state, dispatch } = useGlobal();

  



  return(
    <Modal visible={modalVisible} transparent={true} animationType="fade">
      <View style={{flex:1,alignItems:"center",justifyContent:'center',backgroundColor:"rgba(0,0,0,0.3)"}}>
        <View style={{marginTop:-100}}>
          <Image
            style={{ width: 320, height: 170}}
            source={require("../../assets/images/profile/v_bg.png")}
          />
          <View style={{ width:320,backgroundColor:'#fff',marginTop:-1,borderBottomLeftRadius:24,borderBottomEndRadius:24,paddingHorizontal:27,paddingBottom:34 }}>
            <View style={{alignItems:'center',flexDirection:'row',marginBottom:16}}>
              <Text style={{fontFamily:'HarmonyOS_Sans_SC_Regular',fontSize:18,color:'#2C2C2E',marginRight:8,fontWeight:'500'}}>更新内容</Text>
              <Text style={{fontFamily:'HarmonyOS_Sans_SC_Regular',fontSize:14,color:'#8E8E93'}}>v{versionInfo.primaryVersionCode}.{versionInfo.secondryVersionCode}.{versionInfo.tertiaryVersionCode}</Text>
            </View>
            <Text style={{fontFamily:'HarmonyOS_Sans_SC_Regular',fontSize:14,color:'#48484A',lineHeight:24}}>{versionInfo.upgradePoint}</Text>

            <View style={{flexDirection:'row',marginTop:24,alignItems:'center',justifyContent:'space-between'}}>
              {
                versionInfo.upgradeMode != 1
                ?
                <TouchableOpacity onPress={()=>{
                  AsyncStorage.setItem('primaryVersionCode',versionInfo.primaryVersionCode.toString())
                  AsyncStorage.setItem('secondryVersionCode',versionInfo.secondryVersionCode.toString())
                  AsyncStorage.setItem('tertiaryVersionCode',versionInfo.tertiaryVersionCode.toString())
                  setModalVisible(false)
                }} style={{width:'47%',borderRadius:12,alignItems:'center',justifyContent:'center',height:44,backgroundColor:'#D1D1D6'}}>
                  <Text style={{fontSize:18,fontWeight:'500',fontFamily:'HarmonyOS_Sans_SC_Regular',color:'#fff'}}>暂时忽略</Text>
                </TouchableOpacity>
                :
                ''
              }
              <TouchableOpacity onPress={()=>{

                Linking.openURL(versionInfo.apkUrl);
                                
              }} style={[{borderRadius:12,alignItems:'center',justifyContent:'center',height:44,backgroundColor:'#3076D9'},versionInfo.upgradeMode != 1 ? {width:'47%'} :{width:'100%'}]}>
                <Text style={{fontSize:18,fontWeight:'500',fontFamily:'HarmonyOS_Sans_SC_Regular',color:'#fff'}}>立即升级</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
       
      </View>
    </Modal>
  )

}




const MadalScreen = ({ modalVisible, setModalVisible }: any) => {
  const [pageNmu, setPageNum] = useState(1);
  const insets = useSafeAreaInsets();

  return (
    <Modal visible={modalVisible} transparent={false} animationType="fade">
      <Pressable
        style={{
          flex: 1,
          backgroundColor: "rgba(0, 0, 0, 0.72)",
          paddingTop: Platform.OS == "ios" ? 0 : 0,
        }}
        onPress={() => {
          setPageNum((pre) => pre + 1);
          // Alert.alert(JSON.stringify(pageNmu))
          if (pageNmu >= 7) {
            setModalVisible(false);
            AsyncStorage.setItem("guideHome", "1");
          }
        }}
      >
        {/* <ImageBackground
          style={{flex:1,backgroundColor:'red'}}
          source={require("../../assets/guidePage/home_1.png")}
        ></ImageBackground> */}
        {pageNmu == 1 ? (
          <Image
            style={{ width: "100%", height: "100%" }}
            source={require("../../assets/guidePage/home_1.png")}
          />
        ) : pageNmu == 2 ? (
          <Image
            style={{ width: "100%", height: "100%" }}
            source={require("../../assets/guidePage/home_2.png")}
          />
        ) : pageNmu == 3 ? (
          <Image
            style={{ width: "100%", height: "100%" }}
            source={require("../../assets/guidePage/home_3.png")}
          />
        ) : pageNmu == 4 ? (
          <Image
            style={{ width: "100%", height: "100%" }}
            source={require("../../assets/guidePage/home_4.png")}
          />
        ) : pageNmu == 5 ? (
          <Image
            style={{ width: "100%", height: "100%" }}
            source={require("../../assets/guidePage/home_5.png")}
          />
        ) : pageNmu == 6 ? (
            <Image
              style={{ width: "100%", height: "100%" }}
              source={require("../../assets/guidePage/home_6.png")}
            />
          )
        :
          pageNmu == 7 ? (
            <Image
              style={{ width: "100%", height: "100%" }}
              source={require("../../assets/guidePage/home_7.png")}
            />
          )
        :
        ''
      }
      </Pressable>
    </Modal>
  );
};

const Home = ({ navigation }: any) => {
  const [modalVisible, setModalVisible] = useState(false);

  const [isLogin, setIsLogin] = useState(false);
  const { state, dispatch } = useGlobal();
  const listRef = useRef(null);

  const fetchData = async () => {
    // 在组件挂载时检查token，如果没有token，则导航到登录页
    let token = await AsyncStorage.getItem("TOKEN");
    let guideHome = await AsyncStorage.getItem("guideHome");

    if (!guideHome) {
      setModalVisible(true);
    }
    // Alert.alert(JSON.stringify(token))
    if (!token) {
      navigation.replace("Login");
      setIsLogin(false);
    } else {
      setIsLogin(true);
      dispatch({ type: "SET_TOKEN", payload: token });
    }
  };

  useEffect(() => {
    // AsyncStorage.removeItem('guideHome')
    fetchData();
    return () => {};
  }, []);
  if (isLogin) {
    return (
      <S.Container style={{ paddingBottom: 0 }}>
        <Header
          iconClick={() => {
            navigation.navigate("Classify");
          }}
          listRef={listRef}
        />
        <Category />
        <View style={{ flex: 1 }}>
          <TasksList ref={listRef} />
        </View>
        <AddTaskButton listRef={listRef} />
        <MadalScreen
          modalVisible={modalVisible}
          setModalVisible={setModalVisible}
        />
        <VersionModal/>
      </S.Container>
    );
  } else {
    return "";
  }
};

export default Home;
